#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class JilinYbcxzzzHunchunPolicy(BaseTaxPolicySpider):
    name = 'jilin_ybcxzzz_hunchun_policy'
    
    province = '吉林省'
    city = '延边朝鲜族自治州'
    park = ''
    # source = '吉林省科学技术厅'
    
    def start_requests(self):
        for source, county, url in [
            ['珲春市人民政府', '珲春市', 'http://www.hunchun.gov.cn/hcszfxxgkw/cyqzf/xxgkml/?stit=%E7%8F%B2%E6%94%BF%E5%8F%91&num=4'],
            ['珲春市人民政府', '珲春市', 'http://www.hunchun.gov.cn/hcszfxxgkw/cyqzf/xxgkml/?stit=%E7%8F%B2%E6%94%BF%E5%8A%9E%E5%8F%91&num=4'],
            ['珲春市工业和信息化局', '珲春市', 'http://www.hunchun.gov.cn/hcszfxxgkw/gzbm/cyqkxjsj/xxgkml/'],
            ['珲春市财政局', '珲春市', 'http://www.hunchun.gov.cn/hcszfxxgkw/gzbm/cyqczj/xxgkml/'],
            ['珲春市人力资源和社会保障局', '珲春市', 'http://www.hunchun.gov.cn/hcszfxxgkw/gzbm/cyqrsj/xxgkml/'],
            ['珲春市商务局', '珲春市', 'http://www.hunchun.gov.cn/hcszfxxgkw/gzbm/cyqrjw/xxgkml/'],
            ['珲春市文化广播电视和旅游局', '珲春市', 'http://www.hunchun.gov.cn/hcszfxxgkw/gzbm/cyqsjj/xxgkml/'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={"item": item})

    def parse_content(self, response, **kwargs):
        # url = 'https://infogate.jl.gov.cn/govsearch/jsonp/gkml_xzgf20221026.jsp?'
        meta = response.meta
        url = response.xpath(""".""").re_first(r"url:\s*\"(http\:\/\/(?!localhost).*)\?") or 'http://111.26.49.117:8081/govsearch/jsonp/gkml/zf_list.jsp'
        url = response.urljoin(url)

        channelId = response.xpath('.').re_first(r'var channelId = "(\d+)";')
        lb = response.xpath('.').re_first(r'var lb = "(\d+)";')
        stit = ''
        params = {
            "page": "1",
            "lb": lb,
            # "callback": "result",
            "sword": stit,
            "searchColumn": "all",
            "channelId": channelId,
            "_": f"{int(time.time() * 1000)}"
        }
        if "stit" in response.url:
            stit = response.url.split('stit=')[1].split('&')[0]
            stit = urllib.parse.unquote(stit)
            if stit.isdigit():
                params["subcat"] = stit
                stit = ''
            else:
                params["searchColumn"] = "wenhao"
            # params["searchColumn"] = "wenhao"
        # print('source', meta.get('source'), stit)
        params["sword"] = stit
        temp_url = url + f'{"&" if "?" in url else "?"}{urllib.parse.urlencode(params)}'
        # print(temp_url)
        meta.update({"params": params, "url": url})
        yield scrapy.Request(temp_url, callback=self.parse_list, meta=meta)

    def parse_list(self, response, **kwargs):
        meta = response.meta
        params = meta.get('params')
        prev_item = meta.get('item')
        try:
            json_data = json.loads(response.text.strip()[7:-2])
        except:
            print(params)
        for elem in json_data['data']:
            item = Item()
            item['source_url'] = elem['puburl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['tip']['dates']
            item['source'] = meta.get('source')
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if meta.get("is_next") is not False:
            total = json_data['num']
            params = meta.get('params')
            url = meta.get('url')
            print('source', prev_item.get('source'), total)
            total_page = math.ceil(int(total) / 15)
            for page_num in range(2, total_page + 1):
                params['page'] = page_num
                params['_'] = f"{int(time.time() * 1000)}"
                temp_url = url + f'{"&" if "?" in url else "?"}{urllib.parse.urlencode(params)}'
                meta.update({'item': prev_item, 'is_next': False, "params": params, "url": url})
                yield scrapy.FormRequest(temp_url, callback=self.parse_list, meta=meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['park'] = self.park
        # item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jilin_ybcxzzz_hunchun_policy".split())
